package com.bawei.hfgc.databinding;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.bawei.hfgc.R;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button but1;
    private Button but2;
    private TextView vmTv;
    private TextViewModel vm;
    private Observer<String> dataob;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         vm = new ViewModelProvider(this, new ViewModelProvider.Factory() {
            @NonNull
            @Override
            public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
                return (T) new TextViewModel();
            }
        }).get(TextViewModel.class);

        initView();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.but1==id){
           vm.data.setValue("hhhhh");
        }
        else {
            String s = vm.data.getValue();
            Log.i("TAG", "onClick: "+s);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
       dataob =  new Observer<String>() {
            @Override
            public void onChanged(String s) {
                vmTv.setText(s);
            }
        };
        vm.data.observe(this, dataob);
    }

    @Override
    protected void onPause() {
        super.onPause();
        vm.data.removeObserver(dataob);
    }

    private void initView() {
        but1 = (Button) findViewById(R.id.but1);
        but2 = (Button) findViewById(R.id.but2);
        vmTv = (TextView) findViewById(R.id.vm_tv);
        but1.setOnClickListener(this::onClick);
        but2.setOnClickListener(this::onClick);
    }
}